package com.mindskip.xzs.utility;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.InvalidClaimException;
import io.jsonwebtoken.Jwts;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class TokenUtil {
    private static final String JWT_KEY = "5e278qhwxDAA232Ei9whjjS.JFnDK.z.[kloiUSih]3nlnfdasf23dmda83/faeajfSIOOIsj934YXio}";

    public static Claims parseToken(String token) throws Exception {
        return (Claims) Jwts.parser().setSigningKey(generateKey()).parseClaimsJws(token).getBody();
    }

    public static SecretKey generateKey() throws Exception {
        byte[] encodedKey = Base64.decodeBase64(JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    public String validateToken(String token) throws ExpiredJwtException, InvalidClaimException, Exception {
        String subject = null;
        if (token.startsWith("Bearer")) {
            token = token.replaceFirst("Bearer", "").trim();
        }

        Claims claims = this.parseToken(token);
        subject = claims.getSubject();
        return subject;
    }
}
